/**
 * Created by wengca on 2016/12/8.
 */

//var express = require('express');
//var router = express.Router();

var request = require('request');
var multiparty = require('multiparty');
var merge = require('merge');
var uuid = require("node-uuid");
var url = require("url");
var fs = require("fs");
var parseBody = require("../common/buildRequestBody.js").commonParseBody;




//单页（首页，登入之类不需要审核判断的）
app.get('/:router', function (req, res) {
    var router = req.params.router;  //第一级目录
    console.log("进入首页",router);
    /*
    *     没有ico前先屏蔽
    * */
    if(router == 'favicon.ico')
        return;

    res.render(router);
});


//单页（首页，登入之类不需要审核判断的）
app.get('/main/template/keypoint.html', function (req, res) {
    var menu = req.params.menu;  //第一级目录
    console.log("进入首页",menu);
    /*
    *     没有ico前先屏蔽
    * */
    if(menu == 'favicon.ico')
        return;
    res.render("main/template/keypoint");
});


//进入页面(不带参数)
app.get('/:master/:directory', function (req, res) {
    var master = req.params.master;  //第一级目录
    var directory = req.params.directory;  //第二级目录
    var url = master + "/" + directory;
    console.log("url is:",url);

    res.render(url);
});


//进入页面(带参数)
app.get('/:master/:directory:data', function (req, res) {
    var master = req.params.master;  //第一级目录
    var directory = req.params.directory;  //第二级目录
    var data = req.params.data;  //第二级目录
    var masterFile = "../control/" + master + ".js";
    var masterModele = require(masterFile);
    masterModele[masterModele](data,function(){

    });
});


//post路由
app.post('/:control/:active', function (req, res) {
    console.log("获得POST链接");
    var master = req.params.control;  //第一级目录
    var directory = req.params.active;  //第二级目录
    console.log(master  + "/" + directory);
    var masterFile = "../control/"+master+".js";
    console.log("control file is:",masterFile);
    var masterModele = require(masterFile);
    console.log("masterModele  is:",masterModele);

    getPostInfo(req,res,function(parame){
        console.log("parame is:",parame)
        masterModele[directory](parame,req,function(info){
            console.log("info is",info);
            var resInfo =info;
            res.end(JSON.stringify(resInfo));
        });
    });
});


//获取参数
var getPostInfo =  function(req,res,cb){
    console.log("获取参数")
    parseBody(req, function(code, msg, data){
        var str = data;
        console.log("str",str);
		if(code == -1){
			 var err = {code: "FALE", msg: "请求参数格式错误"}
            res.writeHead(200, {"Content-Type": "text/plain", charset: 'utf-8'});
            err = JSON.stringify(err);
            return res.end(err);
		}
        cb(str)
    });
};

//module.exports = router;